import { defineStore } from 'pinia';
import helper from "@/sheep/helper"
import router from "@/sheep/router"
import userApi from "@/sheep/api/user"
import isEmpty from 'lodash/isEmpty';
import cloneDeep from 'lodash/cloneDeep';
import clone from 'lodash/clone';
import { closeAuthModal } from '@/sheep/hooks/useModal';


// 默认用户信息
const defaultUserInfo = {
	nickname:''
};


const user = defineStore({
  id: 'user',
  state: () => ({
    userInfo: defaultUserInfo, // 用户信息
    isLogin: !!uni.getStorageSync('token'), // 登录状态
  }),

  actions: {
	// 获取个人信息
	async getInfo() {
	  const { code,data } = await userApi.getUserInfo();
	  if(code !== 1) return
 	  this.userInfo = data; 
	  return Promise.resolve(data);
	},
	// 获取个人信息
	async editUserInfo(infoObj = {}) {
	 if(!infoObj && !Object.keys(infoObj).length) return this.getInfo()
	  const { code,data } = await userApi.editProfile(infoObj);
	  if(code !== 1) return
	 setTimeout(() => this.getInfo(),800)
	  return Promise.resolve(data);
	},
	async login(){
		let code = await helper.getCode()
		 userApi.minilogin({code,inviter_code:this.shareUserId}).then( res => {
			 this.setToken(res.data?.userinfo?.token)
			 // closeAuthModal()
			 router.back()
		 })
	},
	// 设置token
	setToken(token = '') {
	  if (token === '') {
	    this.isLogin = false;
	    uni.removeStorageSync('token');
	  } else {
	    this.isLogin = true;
	    uni.setStorageSync('token', token);
	    this.loginAfter();
	  }
	  return this.isLogin;
	},
	// 登录后
	loginAfter() {
	  if(!this.isLogin) return
	  router.go('/pages/index/index')
	  this.getInfo()
	},
	resetUserData(showToast = false){
		this.isLogin = false
		uni.removeStorageSync('token')
		this.userInfo = cloneDeep(defaultUserInfo)
		if(showToast) {
			helper.toast('退出成功')
			setTimeout(() => {
				uni.navigateTo({
					url:'/pages/login/login'
				})
			},1000)
		} 
	},
	// 登出
	async logout(force = false) {
		uni.showModal({
			cancelColor:"#666666",
			confirmColor:"#33D65E",
			title: '温馨提示',
			content:"确定要退出登录吗？",
			success: async (res) => {
				if (res.confirm) {
					this.resetUserData(true);
					uni.hideLoading()
				}
			}
		})
	  return !this.isLogin;
	},
	async dopay(order_id = ''){
		if(!order_id) return
		const { code,data } = await orderApi.dopay({order_id})	
		return new Promise((resolve,reject) => {
			if(code !== 1) resolve(false)
			uni.requestPayment({
				...data,
				success: () => {
					helper.toast('支付成功')
					resolve(true)
				},
				fail: () => {
					helper.toast('支付失败')
					resolve(false)
				}
			})
		})
	}
  },
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'user-store',
      },
    ],
  },
});

export default user;
